// src/utils/api.js
import { useMessage } from 'naive-ui'
import { API_CONFIG } from '@/config/api.js'

class FlowAPI {
  constructor() {
    this.message = useMessage()
  }

  async chatCompletions(apiKey, config) {
    try {
      const baseURL = config.baseURL || API_CONFIG.IFLOW.BASE_URL
      
      console.log('API调用参数:', {
        baseURL,
        model: config.model,
        messagesLength: config.messages.length,
        temperature: config.temperature,
        max_tokens: config.max_tokens
      })

      const response = await fetch(`${baseURL}/chat/completions`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: config.model,
          messages: config.messages,
          temperature: config.temperature,
          max_tokens: config.max_tokens,
          stream: false
        })
      })

      console.log('API响应状态:', response.status, response.statusText)

      if (!response.ok) {
        const errorText = await response.text()
        console.error('API错误响应:', errorText)
        throw new Error(`API请求失败: ${response.status} ${response.statusText}`)
      }

      const data = await response.json()
      console.log('API成功响应:', data)
      
      if (data.error) {
        throw new Error(data.error.message || 'API返回错误')
      }

      if (!data.choices || !data.choices[0]) {
        throw new Error('API返回数据格式错误')
      }

      return data.choices[0].message.content
    } catch (error) {
      console.error('API调用错误:', error)
      this.message.error(`对话失败: ${error.message}`)
      throw error
    }
  }

  // 修复测试连接逻辑
  async testConnection(apiKey, model, baseURL = API_CONFIG.IFLOW.BASE_URL) {
    try {
      console.log('测试连接参数:', { apiKey: apiKey ? '已设置' : '未设置', model, baseURL })
      
      const response = await fetch(`${baseURL}/chat/completions`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: model,
          messages: [{ role: 'user', content: 'Hello' }],
          temperature: 0.1,
          max_tokens: 10
        })
      })

      console.log('测试连接响应状态:', response.status)

      if (response.status === 434) {
        // 专门处理 API 密钥错误
        const errorData = await response.json()
        throw new Error(errorData.msg || 'API密钥无效')
      }

      if (!response.ok) {
        throw new Error(`测试连接失败: ${response.status}`)
      }

      const data = await response.json()
      console.log('测试连接成功:', data)
      
      return true
    } catch (error) {
      console.error('测试连接错误:', error)
      throw error
    }
  }
}

export const flowAPI = new FlowAPI()